﻿using ELS.Models;
using System.Data.SQLite;
using System.Data;
using Dapper;

namespace ELS.Services
{
	public interface ISqliteDataService
	{
		Task<T> Get<T>(string uri);
		Task Post(string uri, object value);
		Task<T> Post<T>(object value);
		Task Put(string uri, object value);
		Task<T> Put<T>(string uri, object value);
		Task Delete(string uri);
		Task<T> Delete<T>(string uri);
	}

	public class SqliteDataService : ISqliteDataService
	{
		private readonly string _connectionString = @"Data Source=.\wwwroot\Database\data.db;Version=3";

		public Task Delete(string uri)
		{
			throw new NotImplementedException();
		}

		public Task<T> Delete<T>(string uri)
		{
			throw new NotImplementedException();
		}

		public Task<T> Get<T>(string uri)
		{
			throw new NotImplementedException();
		}

		public Task Post(string uri, object value)
		{
			throw new NotImplementedException();
		}

		public async Task<T> Post<T>(object value)
		{
			using (IDbConnection db = new SQLiteConnection(_connectionString))
			{
				string sqlQuery = "SELECT * FROM User where Username = @Username AND Password = @Password";
				var result = await db.QueryAsync<T>(sqlQuery, value);
				if (result == null|| result.Count() == 0)
				{
					throw new Exception("用户名或密码错误，请重新输入！");
				}

				return result.FirstOrDefault();
			}
		}

		public Task Put(string uri, object value)
		{
			throw new NotImplementedException();
		}

		public Task<T> Put<T>(string uri, object value)
		{
			throw new NotImplementedException();
		}
	}
}
